package com.atguigu.tingshu.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private KafkaService kafkaService;


	/**
	 * 获取当前用户对某个声音播放进度
	 * @param trackId
	 * @param userId
	 * @return
	 */
	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		// 1. 创建查询条件
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(trackId));

		// 2.获取播放进度
		UserListenProcess userListenProcess = mongoTemplate.findOne(query,UserListenProcess.class,
				MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId));
		if (userListenProcess != null){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0.00");
	}

	/**
	 * 更新声音播放进度
	 * @param userId
	 * @param userListenProcessVo
	 */
	@Override
	public void updateListenProcess(Long userId, UserListenProcessVo userListenProcessVo) {
		// 1. 根据用户ID+声音ID查询播放进度
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId).and("trackId").is(userListenProcessVo.getTrackId()));

		// 2. 获取播放进度
		UserListenProcess userListenProcess = mongoTemplate.findOne(query,UserListenProcess.class,
				MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId));
		if (userListenProcess != null){
			// 2.1 如果播放进度存在 更新播放进度
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setUpdateTime(new Date());
		}else {
			// 2.2 如果播放进度记录不存在 新增播放进度
			userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}
		mongoTemplate.save(userListenProcess,MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS,userId));

		// 3. 发送MQ消息到Kafka通知专辑服务，更新声音、专辑、播放量累加
		// 3.1 同一个用户同一声音当天只能累加一次播放量 set EX(过期时间单位秒) NX(当key不存在才能存入成功)
		String key = "user_process" + userId + "_" + userListenProcessVo.getTrackId();
		long time = DateUtil.endOfDay(new Date()).getTime();
		long ttl = time - System.currentTimeMillis();
		Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", ttl, TimeUnit.MILLISECONDS);
		if (flag){
			// 3.2 封装更新统计数值对象
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setAlbumId(userListenProcessVo.getAlbumId());
			trackStatMqVo.setTrackId(userListenProcessVo.getTrackId());
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setCount(1);
			trackStatMqVo.setBusinessNo(RedisConstant.BUSINESS_PREFIX + IdUtil.fastSimpleUUID());

			// 3.3 发送消息到更新声音统计话题中
			kafkaService.sendKafkaMessage(KafkaConstant.QUEUE_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));

		}
	}

	/**
	 * 获取当前用户最近播放专辑及声音ID
	 * @return
	 */
	@Override
	public Map<String, Long> getLatelyTrack() {
		// 1. 获取当前用户ID
		Long userId = AuthContextHolder.getUserId();
		// 2. 根据用户ID+更新时间倒序获得最近一条播放进度
		Query query = new Query();
		query.addCriteria(Criteria.where("userId").is(userId));
		query.with(Sort.by(Sort.Direction.DESC,"updateTime"));
		query.limit(1);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class,
				MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId));
		if (userListenProcess != null){
			// 3. 从播放进度中获取专辑ID，声音ID
			Map<String,Long> map = new HashMap<>();
			map.put("albumId",userListenProcess.getAlbumId());
			map.put("trackId",userListenProcess.getTrackId());
			return map;
		}
		return null;
	}

}
